package com.personal.downloadbooks.demos.web.service.impl;


import com.personal.downloadbooks.demos.web.model.DownloadBooks;
import com.personal.downloadbooks.demos.web.properties.DownloadBooksProperties;
import com.personal.downloadbooks.demos.web.service.ParseUrlService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Arrays;

@Service
public class ParseUrlServiceImpl implements ParseUrlService {

    @Autowired
    private DownloadBooksProperties downloadBooksProperties;
    
    @Override
    public DownloadBooks parseBookInfo(String url) {
        try {
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(downloadBooksProperties.getSocksProxyHost(), downloadBooksProperties.getSocksProxyPort()));

            // 1. 请求主页
            Document doc = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0")
                    .timeout(10000)
                    .proxy(proxy)
                    .get();

            // mainFileName
            String mainFileName = doc.select(".gallery_top .info h2").text().replace("/","");

            // endPage
            String endPageStr = doc.select(".gallery_top .info ul li:nth-last-child(2) span.tags span.tag_name.pages").text();
            int endPage = Integer.parseInt(endPageStr);

            // 2. 获取第一页跳转链接
            String firstPageHref = doc.select(".outer_thumbs .gallery_thumbs .gt_th a").first().attr("href");
            String firstPageUrl = "https://nhentai.xxx" + firstPageHref;

            // 3. 请求第一页页面，获取隐藏字段
            Document firstDoc = Jsoup.connect(firstPageUrl)
                    .userAgent("Mozilla/5.0")
                    .timeout(10000)
                    .proxy(proxy)
                    .get();

            String imageDir = firstDoc.select("input#image_dir").attr("value");
            String galleryId = firstDoc.select("input#gallery_id").attr("value");
            String serverId = firstDoc.select("input#server_id").attr("value");

            // 4. 构建图片前缀 URL
            String imagePrefix = String.format("https://i%s.nhentaimg.com/%s/%s/", serverId, imageDir, galleryId);

            // 5. 构建 DownloadBooks
            DownloadBooks books = new DownloadBooks();
            books.setMainFileName(mainFileName);
            books.setBeginPage(1);
            books.setEndPage(endPage);
            books.setPictureType(Arrays.asList(".webp", ".jpg", ".png", ".gif"));
            books.setImageUrl(imagePrefix);

            return books;
        } catch (Exception e) {
            throw new RuntimeException("解析失败: " + e.getMessage(), e);
        }
    }
}
